<template>
  <div class="center-screen">钉钉自动登录中,请稍后...</div>
</template>
<script setup lang="ts">
import dd from "dingtalk-jsapi";
import { feature } from "@/utils/axios-utils";
import dingAuthApi from "@/api-services/apis/authExtra/dingAuthApi";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { HOME_URL } from "@/config";
const router = useRouter();
const loading = ref(false);
const getDingdingAuthCode = () => {
  return new Promise<string>((resolve, reject) => {
    dd.getAuthCode({
      corpId: "dingCorpId",
      success: (res: any) => {
        resolve(res.code);
      },
      fail: (err: any) => {
        ElMessage.error(err);
        reject(err);
      }
    });
  });
};

const dingdingLogin = async () => {
  try {
    const userStore = useUserStore();
    if (!userStore.accessToken) {
      let authCode = await getDingdingAuthCode();
      if (authCode) {
        const [err] = await feature(dingAuthApi.login(authCode));
        if (err) {
          ElMessage.error(err.message);
          ElMessageBox.confirm("钉钉自动登录失败，将跳转至登录界面", "提示", { type: "warning" })
            .then(() => {
              router.push("/login");
            })
            .catch(() => {
              router.push("/login");
            });
          return;
        }
      } else {
        ElMessageBox.confirm("钉钉获取授权码失败，将跳转至登录界面", "提示", { type: "warning" })
          .then(() => {
            router.push("/login");
          })
          .catch(() => {
            router.push("/login");
          });
        return;
      }
    }
    // 2.添加动态路由
    await initDynamicRouter();

    let url = HOME_URL;
    router.push(url);
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  loading.value = true;
  setTimeout(async () => {
    await dingdingLogin();
  }, 200);
});
</script>
<style>
.center-screen {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  font-size: 20px;
}
</style>
